<template>
    <van-nav-bar :title="pageData.title" left-arrow @click-left="onClickLeft" @click-right="onClickRight">
        <template #right>
            <van-icon name="wap-home-o" size="18" />
        </template>
    </van-nav-bar>
    <div class="pd30">
        <div class="special-banner">
            <div class="banner">
                <van-image :src="pageData.breviaryimges" fit="cover" height="194" width="100%" />
            </div>
            <div class="banner-title">
                {{ pageData.title }}
            </div>
        </div>
        <div class="special-info">
            <p> {{ pageData.notes }} </p>
        </div>
    </div>
    <div class="special-tabs">
        <van-tabs
            v-if="pageData.columnews && pageData.columnews.length"
            v-model:active="active"
            scrollspy
            sticky
            shrink
        >
            <van-tab
                v-for="(column, idx) in pageData.columnews"
                :key="column.columnid || idx"
                :title="column.columnname"
            >
                <van-list>
                    <van-cell
                        v-for="item in column.news"
                        :key="item.newsid"
                        class="news-box"
                    >
                        <nuxt-link :to="`/news/${item.newsid}`" class="flex">
                            <div class="news-text">
                                <h2 class="title">{{ item.title }}</h2>
                                <p class="date">{{ safeFormatRelativeTime(item.releasetime) }}</p>
                            </div>
                            <div class="news-img">
                                <van-image :src="item.breviaryimges" width="128" height="72" fit="cover" />
                            </div>
                        </nuxt-link>
                    </van-cell>
                </van-list>
            </van-tab>
        </van-tabs>
        <div v-else class="pd30">暂无专题内容</div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { navigateTo, useRoute, useAsyncData } from 'nuxt/app';
import { formatRelativeTime } from '../../utils/timeUtils'; // 复用 utils 中的时间工具

interface NewsItem {
  newsid: string;
  title: string;
  releasetime?: string;
  breviaryimges?: string;
  [key: string]: any;
}

interface PageData {
  title?: string;
  breviaryimges?: string;
  notes?: string;
  columnews?: Array<{
    columnid?: string;
    columnname?: string;
    news?: NewsItem[];
  }>;
  [key: string]: any;
}

const route = useRoute();
const newsId = computed(() => String(route.params.special || ''));

const active = ref(0);
const onClickLeft = () => history.back();
const onClickRight = () => navigateTo('/');

// 使用 Nuxt 的 useAsyncData 自动处理 loading / error / 缓存 / SSR
const { data: rawData, pending, error, refresh } = useAsyncData(
  () => `news-detail-${newsId.value}`,
  () => $fetch('/api/news/detail', { params: { newsid: newsId.value } }),
  { watch: [newsId] }
);

// 从响应里安全取出 pageData（防止 data 结构变化报错）
const pageData = computed<PageData>(() => {
  const resp = rawData.value as any;
  return resp?.data?.[0] ?? {};
});

// 便捷的列表安全访问器
const columns = computed(() => pageData.value.columnews ?? []);

//时间格式化
const dayjs = useDayjs();

const safeFormatRelativeTime = (time: string | null | undefined) => {
  if (!time) return '';
  const now = dayjs();
  const target = dayjs(time);
  
  // 如果是当天时间，显示相对时间（如 "2 小时前"）
  if (target.isSame(now, 'day')) {
    return target.fromNow();
  } 
  // 非当天时间，显示完整年月日（如 "2023-01-01"）
  return target.format('YYYY-MM-DD');
};

// 重试函数（供模板按钮调用）
function retry() {
  refresh();
}

// 组件挂载时无需手动触发请求（useAsyncData 会自动触发），但保留 onMounted 用于其它初始化
onMounted(() => {
  // 可执行其他初始化逻辑
});
</script>


<style scoped>
.news-box :deep(.van-cell__value){
    text-align: left;
}
.special-banner {
    position: relative;
    margin-bottom: 15px;
}

.banner-title {
    background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, #000000 100%);
    padding: 16px 12px;
    position: absolute;
    bottom: 0;
    left: 0;
    width: calc(100% - 24px);
    color: #fff;
    font-size: 20px;
    line-height: 26px;
}

.special-info {
    font-size: 15px;
    line-height: 21px;
    color: #666;
}

:deep(.van-tab__panel) {
    background: #f9f9f9; 
}

:deep(.van-index-bar__sidebar) {
    position: relative;
    flex-direction: row;
}
</style>